const express = require('express');
const router = express.Router();
const connection = require('../config/database');

// 获取所有进货单
router.get('/', (req, res) => {
  const query = `
    SELECT po.*, d.name as dealer_name 
    FROM purchase_orders po
    LEFT JOIN dealers d ON po.dealer_id = d.id
    ORDER BY po.order_date DESC
  `;
  
  connection.query(query, (err, results) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(results);
  });
});

// 获取进货单详情
router.get('/:id', (req, res) => {
  const orderId = req.params.id;
  
  // 获取进货单基本信息
  const orderQuery = `
    SELECT po.*, d.name as dealer_name 
    FROM purchase_orders po
    LEFT JOIN dealers d ON po.dealer_id = d.id
    WHERE po.id = ?
  `;
  
  // 获取进货单明细
  const itemsQuery = `
    SELECT poi.*, 
      CASE 
        WHEN poi.item_type = 'book' THEN b.title
        ELSE g.name
      END as item_name
    FROM purchase_order_items poi
    LEFT JOIN books b ON poi.item_type = 'book' AND poi.item_id = b.isbn
    LEFT JOIN goods g ON poi.item_type = 'goods' AND poi.item_id = g.code
    WHERE poi.purchase_order_id = ?
  `;

  connection.query(orderQuery, [orderId], (err, orders) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }

    if (orders.length === 0) {
      res.status(404).json({ error: '进货单不存在' });
      return;
    }

    connection.query(itemsQuery, [orderId], (err, items) => {
      if (err) {
        res.status(500).json({ error: err.message });
        return;
      }

      res.json({
        ...orders[0],
        items: items
      });
    });
  });
});

// 创建进货单
router.post('/', (req, res) => {
  const { dealer_id, items, notes } = req.body;
  
  // 验证数据
  if (!dealer_id || !Array.isArray(items) || items.length === 0) {
    res.status(400).json({ error: '无效的请求数据' });
    return;
  }

  // 验证每个商品的数据
  for (const item of items) {
    if (!item.type || !item.id || !item.quantity || !item.unit_price) {
      res.status(400).json({ error: '商品数据不完整' });
      return;
    }
    // 确保数值类型正确
    item.quantity = parseInt(item.quantity);
    item.unit_price = parseFloat(item.unit_price);
    item.discount = parseFloat(item.discount || 1);
    
    if (isNaN(item.quantity) || isNaN(item.unit_price) || isNaN(item.discount)) {
      res.status(400).json({ error: '商品数据格式错误' });
      return;
    }
  }

  // 生成订单号 (年月日 + 4位随机数)
  const order_number = new Date().toISOString().slice(0,10).replace(/-/g,'') 
    + Math.floor(Math.random() * 10000).toString().padStart(4, '0');

  // 计算总金额，确保使用数值计算
  const total_amount = items.reduce((sum, item) => {
    const itemTotal = item.quantity * item.unit_price * item.discount;
    return sum + (isNaN(itemTotal) ? 0 : itemTotal);
  }, 0);

  const order = {
    order_number,
    dealer_id,
    total_amount,
    notes,
    status: 'completed'
  };

  connection.beginTransaction(err => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }

    // 插入进货单
    connection.query('INSERT INTO purchase_orders SET ?', order, (err, result) => {
      if (err) {
        connection.rollback(() => {
          res.status(500).json({ error: err.message });
        });
        return;
      }

      const purchase_order_id = result.insertId;

      // 插入进货单明细，确保所有数值都是有效的数字
      const itemValues = items.map(item => [
        purchase_order_id,
        item.type,
        item.id,
        item.quantity,
        item.unit_price,
        item.discount,
        parseFloat((item.quantity * item.unit_price * item.discount).toFixed(2))
      ]);

      const itemsQuery = `
        INSERT INTO purchase_order_items 
        (purchase_order_id, item_type, item_id, quantity, unit_price, discount, total_price)
        VALUES ?
      `;

      connection.query(itemsQuery, [itemValues], (err) => {
        if (err) {
          connection.rollback(() => {
            res.status(500).json({ error: err.message });
          });
          return;
        }

        // 更新库存
        const updatePromises = items.map(item => {
          const updateQuery = item.type === 'book' 
            ? 'UPDATE books SET quantity = quantity + ? WHERE isbn = ?'
            : 'UPDATE goods SET quantity = quantity + ? WHERE code = ?';
          
          return new Promise((resolve, reject) => {
            connection.query(updateQuery, [item.quantity, item.id], (err) => {
              if (err) reject(err);
              else resolve();
            });
          });
        });

        Promise.all(updatePromises)
          .then(() => {
            connection.commit(err => {
              if (err) {
                connection.rollback(() => {
                  res.status(500).json({ error: err.message });
                });
                return;
              }
              res.json({ 
                message: '进货单创建成功', 
                order_id: purchase_order_id 
              });
            });
          })
          .catch(err => {
            connection.rollback(() => {
              res.status(500).json({ error: err.message });
            });
          });
      });
    });
  });
});

module.exports = router; 